package middleware

import (
	"encoding/json"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/rest/httpx"
	"gozero-demo/user/internal/biz"
	"net/http"
	"strconv"
)

type TokenMiddleWareMiddleware struct {
	Redis *redis.Redis
}

func NewTokenMiddleWareMiddleware(redis *redis.Redis) *TokenMiddleWareMiddleware {
	return &TokenMiddleWareMiddleware{
		Redis: redis,
	}
}

func (m *TokenMiddleWareMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		headerToken := r.Header.Get(`Authorization`)
		//1、获取userId
		userId, err := r.Context().Value("userId").(json.Number).Int64()
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, biz.UserAuthError)
			return
		}
		//2、检查redis中的token
		redisToken, err := m.Redis.GetCtx(r.Context(), "token:"+strconv.FormatInt(userId, 10))
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, biz.RedisFail)
			return
		}
		if headerToken != redisToken {
			httpx.ErrorCtx(r.Context(), w, biz.UserLoginError)
			return
		}
		next(w, r)
	}
}
